package com.xx.happychatboot.middleware.springsecurity.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xx.happychatboot.middleware.springsecurity.domain.vo.response.AuthResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义失败处理类
 */
@Component
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException exception) throws IOException, ServletException {
        AuthResponse authResponse = new AuthResponse(HttpServletResponse.SC_UNAUTHORIZED,"用户名或密码错误");
        response.setContentType("application/json;charset=UTF-8");
        String s = new ObjectMapper().writeValueAsString(authResponse);
        response.getWriter().println(s);
    }
}
